# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:  smalleel-api-tools
# FileName:     emailUtil.py
# Author:      
# Datetime:    2023/1/30 15:14
# Description：发送邮件封装

# -----------------------------------------------------------------------------------


import os
import smtplib
import time
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class SendEmail:
    """Send mail"""

    def __init__(self, host, user, password, port=465):
        """
        :param host: smtp server address
        :param port: smtp server report
        :param user: Email account number
        :param password: SMTP service authorization code of mailbox
        """
        if port == 465 or port == 587:
            self.smtp = smtplib.SMTP_SSL(host=host, port=port)
        else:
            self.smtp = smtplib.SMTP(host=host, port=port)
        self.smtp.login(user=user, password=password)
        self.user = user

    def send_email(self, subject="test report", content=None, filename=None, to_addrs=None):
        """
        :param subject:Email subject
        :param content: Email content
        :param filename: Attachment document
        :param to_addrs: Addressee's address
        :type to_addrs: str or list
        :return:
        """
        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["From"] = self.user
        if isinstance(to_addrs, str):
            msg["To"] = to_addrs
        elif to_addrs and isinstance(to_addrs, list):
            msg["To"] = to_addrs[0]
        if not content:
            content = time.strftime("%Y-%m-%d-%H_%M_%S") + ":测试报告"
        text = MIMEText(content, _subtype="html", _charset="utf8")
        msg.attach(text)
        if filename and os.path.isfile(filename):
            with open(filename, "rb") as f:
                content = f.read()
            try:
                report = MIMEApplication(content, _subtype=None)
            except TypeError:
                report = MIMEApplication(content)
            name = os.path.split(filename)[1]
            report.add_header('content-disposition', 'attachment', filename=name)
            msg.attach(report)
        try:
            self.smtp.send_message(msg, from_addr=self.user, to_addrs=to_addrs)
        except Exception as e:
            print("Failed to send test report")
            raise e
        else:
            print("The test report has been sent")
